import os
from django.shortcuts import render, redirect
import paramiko

import AppManager.Mysql
from AppManager import views as AMan_views
from HostManager.SSH import SshComm
from OpManager import settings
from Logs import views as Logs_views


def UploadSftp(RemoteHost: dict, LocalFilePath: str, RemoteFilePath: str):
    if os.path.isdir(LocalFilePath):
        return UploadSftp_DIr(RemoteHost, LocalFilePath, RemoteFilePath)
    elif os.path.isfile(LocalFilePath):
        transport = paramiko.Transport((RemoteHost["host"], RemoteHost["port"]))
        transport.connect(username=RemoteHost["username"], password=RemoteHost["password"])
        sftp = paramiko.SFTPClient.from_transport(transport)
        sftp.put(LocalFilePath, RemoteFilePath)
        transport.close()
        return 1
    else:
        return 0


def UploadSftp_DIr(RemoteHost: dict, LocalFilePath: str, RemoteRootPath: str):
    LocalFilePath = LocalFilePath.replace("\\", "/")
    RemoteRootPath = RemoteRootPath.replace("\\", "/")
    AllPaths = os.walk(LocalFilePath)
    transport = paramiko.Transport((RemoteHost["host"], RemoteHost["port"]))
    transport.connect(username=RemoteHost["username"], password=RemoteHost["password"])
    sftp = paramiko.SFTPClient.from_transport(transport)

    for path, dirlist, filelist in AllPaths:
        newpath = path.replace(LocalFilePath, "")
        for dir_name in dirlist:
            tmp_DirPath = os.path.join(RemoteRootPath + newpath, dir_name)
            print("目录:", tmp_DirPath)
            try:
                sftp.mkdir(tmp_DirPath)
            except FileNotFoundError:
                command = ["mkdir -p " + tmp_DirPath]
                SshComm(RemoteHost["host"], RemoteHost["port"], RemoteHost["username"], RemoteHost["password"], command)
            except Exception as e:
                print(e)
        for file_name in filelist:
            local_FilePath = os.path.join(path, file_name)
            remote_FilePath = os.path.join(RemoteRootPath + newpath, file_name)
            print("文件:", remote_FilePath)
            sftp.put(local_FilePath, remote_FilePath)
    transport.close()
    return 1


@settings.auth(AuthType="HostManager", AuthNum=1)
def AddHost(requests):
    context = {}
    if requests.method == 'GET':
        return render(requests, 'AddHost.html', context)
    else:
        sql = "SELECT * FROM `host` WHERE hostname='%s'" % (requests.POST['hostname'])
        res = AppManager.Mysql.MysqlPool(sql, 1)
        if res:
            context = {
                "hostname_error": "is-invalid"
            }
            return render(requests, 'AddHost.html', context)
        else:
            sql = "INSERT into host (hostname,ip,ssh_port,type,visiblename,description) VALUES ('%s'," \
                  "'%s','%s','%s','%s','%s')" % (
                      requests.POST['hostname'], requests.POST['ip'], requests.POST['ssh_port'],
                      requests.POST['Centos'],
                      requests.POST['visiblename'], requests.POST['description'])
            AppManager.Mysql.MysqlPool(sql, 0)
            sql = "INSERT into host_dev (hostname,Suser,Spasswd) VALUES ('%s','%s','%s')" % (
                requests.POST['hostname'], requests.POST['Suser'], requests.POST['Spasswd'])
            AppManager.Mysql.MysqlPool(sql, 0)
            context = {
                "success": "添加主机: \"" + requests.POST['hostname'] + "\" 成功"
            }
            logtext = "新增主机：(主机名：" + requests.POST['hostname'] + " IP:" + requests.POST['ip'] + " 端口:" + requests.POST[
                'ssh_port'] + " 版本:Centos" + requests.POST['Centos'] + " 可视名:" + requests.POST['visiblename'] + " 备注:" + \
                requests.POST['description'] + ")"
            Logs_views.log(logtext, "SysLog", requests.COOKIES.get('user'))
            return render(requests, 'AddHost.html', context)


@settings.auth(AuthType="HostManager", AuthNum=2)
def HostManager(requests):
    sql = "SELECT * FROM `host`"
    allres = AppManager.Mysql.MysqlPool(sql, 99)
    print(allres)
    if requests.method == 'GET':
        context = {
            "HostList": allres
        }
        return render(requests, 'HostManager.html', context)
    else:
        sql = "SELECT * FROM `host` WHERE hostname='%s' AND id='%s'" % (requests.POST['hostname'], requests.POST['id'])
        selfres = AppManager.Mysql.MysqlPool(sql, 1)
        sql = "SELECT * FROM `host` WHERE hostname='%s'" % (requests.POST['hostname'])
        res = AppManager.Mysql.MysqlPool(sql, 1)
        if not selfres and res:
            context = {
                "hosterror": requests.POST['hostname'] + "已存在",
                "hostname_error": "is-invalid",
                "HostList": allres
            }
            return render(requests, 'HostManager.html', context)
        else:
            sql = "UPDATE host SET hostname='%s',ip='%s',ssh_port='%s',type='%s',visiblename='%s'," \
                  "description='%s' WHERE id=%s" % (
                      requests.POST['hostname'], requests.POST['ip'], requests.POST['ssh_port'],
                      requests.POST['Centos'],
                      requests.POST['visiblename'], requests.POST['description'], requests.POST['id'])
            print(sql)
            AppManager.Mysql.MysqlPool(sql, 0)
            logtext = "主机修改为：(主机名：" + requests.POST['hostname'] + " IP:" + requests.POST['ip'] + " 端口:" + requests.POST[
                'ssh_port'] + " 版本:Centos" + requests.POST['Centos'] + " 可视名:" + requests.POST['visiblename'] + " 备注:" + \
                requests.POST['description']
            if requests.POST['Suser']:
                sql = "UPDATE host_dev SET Suser='%s' WHERE hostname='%s'" % (
                    requests.POST['Suser'], requests.POST['hostname'])
                AppManager.Mysql.MysqlPool(sql, 0)
                logtext += " 修改了Suser"
            if requests.POST['Spasswd']:
                sql = "UPDATE host_dev SET SpasswdVALUES='%s' WHERE hostname='%s'" % (
                    requests.POST['Spasswd'], requests.POST['hostname'])
                AppManager.Mysql.MysqlPool(sql, 0)
                logtext += " 修改了密码"
            Logs_views.log(logtext + ")", "HostLog", requests.COOKIES.get('user'))
            return redirect('/hostmanager')


@settings.auth(AuthType="HostManager", AuthNum=2)
def HostDel(requests):
    if requests.method == 'GET':
        return redirect('/hostmanager')
    else:
        sql = "DELETE FROM host WHERE id=%s;" % (requests.POST['id'])
        AppManager.Mysql.MysqlPool(sql, 0)
        logtext = "删除主机：(主机ID：" + requests.POST['id'] + " 主机名：" + requests.POST['hostname'] + ")"
        Logs_views.log(logtext, "HostLog", requests.COOKIES.get('user'))
        return redirect('/hostmanager')


@settings.auth(AuthType="HostManager", AuthNum=3)
def HostLogs(requests):
    logdict = Logs_views.getlog("HostLog")
    context = {
        "logdict": logdict
    }

    return render(requests, 'HostLogs.html', context)
